<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="质保开始日期" prop="warrantyStartDate">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.warrantyStartDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择质保开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="质保结束日期" prop="warrantyEndDate">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.warrantyEndDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择质保结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="ASIN" prop="asin">
        <el-input
          v-model="queryParams.asin"
          placeholder="请输入ASIN"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="创建人" prop="createdBy">-->
        <!--<el-input-->
          <!--v-model="queryParams.createdBy"-->
          <!--placeholder="请输入创建人"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="创建时间" prop="createdTime">-->
        <!--<el-date-picker clearable size="small" style="width: 200px"-->
          <!--v-model="queryParams.createdTime"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择创建时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="创建时间" prop="lastUpdatedBy">-->
        <!--<el-input-->
          <!--v-model="queryParams.lastUpdatedBy"-->
          <!--placeholder="请输入创建时间"-->
          <!--clearable-->
          <!--size="small"-->
          <!--@keyup.enter.native="handleQuery"-->
        <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="更新时间" prop="lastUpdatedTime">-->
        <!--<el-date-picker clearable size="small" style="width: 200px"-->
          <!--v-model="queryParams.lastUpdatedTime"-->
          <!--type="date"-->
          <!--value-format="yyyy-MM-dd"-->
          <!--placeholder="选择更新时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ymx:ymxasintemplateinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ymx:ymxasintemplateinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ymx:ymxasintemplateinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ymx:ymxasintemplateinfo:export']"
        >导出</el-button> -->
        <el-button
          type="warning"
          icon="el-icon-upload2"
          size="mini"
          @click="excelUploadModal = true"
        >导入</el-button>

      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ymxasintemplateinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="模板表主键" align="center" prop="asinTemplateId" />-->
      <el-table-column show-overflow-tooltip label="ASIN" align="center" prop="asin" />
      <el-table-column show-overflow-tooltip label="产品名称" align="center" prop="orderName" />
      <el-table-column label="产品图片" align="center" prop="orderImage">
        <template slot-scope="scope">
          <span><img v-if="scope.row.orderImage" :src="scope.row.orderImage" alt="" style="max-width: 150px; max-height: 200px"></span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="礼物模板名称" align="center" prop="templateId" >
        <template slot-scope="scope">
          <span>{{ parseGift(scope.row.templateId) }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="折扣码" align="center" prop="discountCode" />
      <!-- <el-table-column show-overflow-tooltip label="质保开始日期" align="center" prop="warrantyStartDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.warrantyStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column show-overflow-tooltip label="质保时长(月)" align="center" prop="warrantyEndDate" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.warrantyEndDate}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="创建人" align="center" prop="createdBy" />-->
      <!--<el-table-column label="创建时间" align="center" prop="createdTime" width="180">-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column label="创建时间" align="center" prop="lastUpdatedBy" />-->
      <!--<el-table-column label="更新时间" align="center" prop="lastUpdatedTime" width="180">-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ parseTime(scope.row.lastUpdatedTime, '{y}-{m}-{d}') }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ymx:ymxasintemplateinfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ymx:ymxasintemplateinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模板主键对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="ASIN" prop="asin">
          <el-input v-model="form.asin" placeholder="请输入ASIN" />
        </el-form-item>
        <el-form-item label="产品名称" prop="orderName">
          <el-input v-model="form.orderName" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="产品图片(URL)" prop="orderImage">
            <span v-if="isTest"></span>
          <div class="uploadBox">
              <input type="file" @change="uploadFile">
              <img v-if="form.orderImage" v-lazy="form.orderImage" :key="form.orderImage" :src="form.orderImage" alt="">
              <i v-else slot="default" class="el-icon-plus"></i>
            </div>
          <!-- <el-input v-model="form.orderImage" placeholder="请输入产品图片地址" /> -->
        </el-form-item>
        <el-form-item label="折扣码" prop="discountCode">
          <el-input v-model="form.discountCode" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="礼物模板名称" prop="templateId">
           <el-select v-model="form.templateId" placeholder="请选择">
            <el-option
              v-for="item in giftTemplateMap"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="质保开始日期" prop="warrantyStartDate">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.warrantyStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择质保开始日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="质保时长（月）" prop="warrantyEndDate">
          <el-input-number v-model="form.warrantyEndDate" label="请输入内容"></el-input-number>
          <!-- <el-input v-model="form.warrantyEndDate" placeholder="请输入内容" /> -->
          <!-- <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.warrantyEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择质保结束日期">
          </el-date-picker> -->
        </el-form-item>
        <!--<el-form-item label="创建人" prop="createdBy">-->
          <!--<el-input v-model="form.createdBy" placeholder="请输入创建人" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="创建时间" prop="createdTime">-->
          <!--<el-date-picker clearable size="small" style="width: 200px"-->
            <!--v-model="form.createdTime"-->
            <!--type="date"-->
            <!--value-format="yyyy-MM-dd"-->
            <!--placeholder="选择创建时间">-->
          <!--</el-date-picker>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="创建时间" prop="lastUpdatedBy">-->
          <!--<el-input v-model="form.lastUpdatedBy" placeholder="请输入创建时间" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="更新时间" prop="lastUpdatedTime">-->
          <!--<el-date-picker clearable size="small" style="width: 200px"-->
            <!--v-model="form.lastUpdatedTime"-->
            <!--type="date"-->
            <!--value-format="yyyy-MM-dd"-->
            <!--placeholder="选择更新时间">-->
          <!--</el-date-picker>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="excelUploadModal" width="400px" append-to-body>
      <p>附件：<el-button type="primary" @click="downTemplate">下载模板</el-button></p>
      <el-upload
        class="upload-demo"
        style="width: 100%"
        :headers="headers"
        :data="{updateSupport:1}"
        :show-file-list="false"
        :on-success="onSuccess"
        drag
        :action="`${baseURL}/ymx/ymxasintemplateinfo/importDatatemplate`"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancelExcelModal">确 定</el-button>
        <el-button @click="cancelExcelModal">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseURL from '@/utils/requestUrl'
import { listYmxasintemplateinfo, getYmxasintemplateinfo, getGiftTemplateMap, delYmxasintemplateinfo, addYmxasintemplateinfo, updateYmxasintemplateinfo, exportYmxasintemplateinfo } from "@/api/ymx/ymxasintemplateinfo";
import axios from 'axios'
import { getToken } from '@/utils/auth'
export default {
  name: "Ymxasintemplateinfo",
  data() {
    return {
      baseURL: baseURL,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isTest: false,
      excelUploadModal: false,
      // 总条数
      total: 0,
      // 模板主键表格数据
      ymxasintemplateinfoList: [],
      giftTemplateMap: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        orderName: null,
        orderImage: null,
        discountCode: null,
        warrantyStartDate: null,
        warrantyEndDate: null,
        asin: null,
        createdBy: null,
        createdTime: null,
        lastUpdatedBy: null,
        lastUpdatedTime: null
      },
      headers: {
        Authorization: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        asin: [
          { required: true, message: '请输入ASIN码', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    console.log(baseURL)
    this.headers.Authorization = 'Bearer ' + getToken();
    this.getList();
    this.getGiftTemplateMap();
  },
  methods: {
    /** 查询模板主键列表 */
    getList() {
      this.loading = true;
      listYmxasintemplateinfo(this.queryParams).then(response => {
        this.ymxasintemplateinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    onSuccess(res, file) {
      if (res.code === 200) {
        this.$message({ message: '导入成功', type: 'success'});
      } else {
        file.status = 'error'
        console.log(file)
        this.$message({ message: res.msg, type: 'error'});
      }
      console.log(res)
    },
    downTemplate() {
      window.open(baseURL + "/profile/upload/%E5%95%86%E5%93%81%E6%A8%A1%E6%9D%BF.xlsx")
    },
    uploadFile(e) {
        this.form.orderImage = '';
        let file = e.target.files[0];
        var formData = new FormData();
        formData.append('file',file);
        axios.post(baseURL + '/common/upload', formData).then(res => {
            if (res.data.code === 200) {
              this.$set(this.form, 'orderImage', res.data.url)
                this.form.orderImage = res.data.url;
                this.isTest = !this.isTest;
                this.$message({ message: '上传成功', type: 'success'});
                // return
                // this.$router.push({path:'/gift', query: {customerInformationId: this.orderData.customerInformationId, asin: this.orderData.asin, orderId: this.orderData.orderId}})
            } else {
                this.$message({ message: '上传失败', type: 'error'});
            }
        })
    },
    getGiftTemplateMap() {
      this.loading = true;
      getGiftTemplateMap().then(response => {
        // this.ymxasintemplateinfoList = response.rows;
        // this.total = response.total;
        let arr = [];
        for(var key in response) {
          arr.push({
            label: key,
            value: response[key]
          })
        }
        this.giftTemplateMap = arr;
        this.loading = false;
      });
    },
    parseGift(value) {
      let str = '';
      this.giftTemplateMap && this.giftTemplateMap.forEach(item => {
        if (item.value === value) {
          str = item.label;
        }
      })
      return str;
    },
    cancelExcelModal() {
      this.excelUploadModal = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        asinTemplateId: null,
        templateId: null,
        orderName: null,
        orderImage: null,
        discountCode: null,
        warrantyStartDate: null,
        warrantyEndDate: null,
        asin: null,
        createdBy: null,
        createdTime: null,
        lastUpdatedBy: null,
        lastUpdatedTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.asinTemplateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const asinTemplateId = row.asinTemplateId || this.ids
      getYmxasintemplateinfo(asinTemplateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.asinTemplateId != null) {
            updateYmxasintemplateinfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addYmxasintemplateinfo(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const asinTemplateIds = row.asinTemplateId || this.ids;
      this.$confirm('是否确认删除模板主键编号为"' + asinTemplateIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delYmxasintemplateinfo(asinTemplateIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有模板主键数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportYmxasintemplateinfo(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style scoped>

.uploadBox{
  width: 200px;
  height: 200px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 38px;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}
.uploadBox input{
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.uploadBox img{
  width: 98%;
  max-height: 300px;
}
</style>
